package client.GUI.dashboard;

import javax.swing.JPanel;

import java.awt.*;
import java.awt.event.*;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;

import client.GUI.GUIConstants;
import client.GUI.GUIClient;
import client.backend.order.Order;
import client.backend.user.UserInformation;

import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.awt.Color;

/**
 * Generates a table of data for all the open orders
 * and allows the user to cancel an existing order.
 *
 */
public class OpenOrderPanel extends JPanel implements ActionListener{
	private static final long serialVersionUID = 1L;
	private JTable table;
	private JButton closeOrder;
    private static OpenOrderPanel instance = null;
    private JScrollPane scrollPane;
    private LinkedList<Order> openOrders;
    
    /**
     * Default Constructor, creates the table and adds the 
     * cancel order objects.
     */
    private OpenOrderPanel() {
    	JLabel title = new JLabel("Open Orders");
    
    	table = createTable();
        createCloseOrders();

    	scrollPane = new JScrollPane(table);
    	scrollPane.setBounds(0,30,512,268);
    	title.setBounds(0, 0, 512, 30);
    	title.setForeground(GUIConstants.Text_Color);
    	title.setHorizontalAlignment(SwingConstants.CENTER);
        
        this.setLayout(null);
        this.setBackground(Color.black);
    	
        this.add(title);
    	this.add(scrollPane);
        this.add(closeOrder);
    }
        

    /**
     * Creates the open orders table
     * 
     * @return void
     */
	public JTable createTable(){
		JTable table = null;
		
		try {
			table = new JTable(new DefaultTableModel(getOpenOrderInfo(), GUIConstants.getOpenOrderColumnNames())){
				private static final long serialVersionUID = 1L;
				//M the table's cells uneditable
				public boolean isCellEditable(int row, int col){		
					return false;
				}
			};
			//Size the table's columns to properly fit the data
			table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
			table.setBounds(0, 0, 512, 304);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return table;
	}
	
	/**
	 * Generates the open order panel from an instance
	 */
	public void refreshTable() {
		if ((scrollPane != null) && (table != null)) {		
			DefaultTableModel model = (DefaultTableModel)table.getModel();
			try {
				model.setDataVector(getOpenOrderInfo(), GUIConstants.getOpenOrderColumnNames());
			} catch (IOException e) {}
			
			scrollPane.updateUI();
			this.updateUI();
		}
	}
	

    public static OpenOrderPanel getInstance() {
    	if (instance == null) {
				instance = new OpenOrderPanel();
		}
    	
		return instance;
    }
    
    /**
     * Checks for actions and performs the appropriate tasks
     */
    public void actionPerformed(ActionEvent e) {
		if (e.getSource() == closeOrder) {
			if(table.getSelectedRow() >= 0 ){
				openOrders.get(table.getSelectedRow()).cancelOrder();
				DashboardPanel.getInstance().refreshTables();
			}
			else{
				GUIClient.getInstance().popupFail("An order must be selected");
			}
		}
    }
    
    /**
     * Returns the table
     * 
     * @return table 
     */
	public JTable getTable() {
		return table;
	}

	/**
	 * Generates an array of the data for the rows
	 * 
	 * @return info[][] - A 2 dimensional array that holds the row data
	 * @throws IOException
	 */
	public String[][] getOpenOrderInfo() throws IOException{
		openOrders = UserInformation.getInstance().getUser().getOpenOrders();
		String[][] info = new String[openOrders.size()][8];
		int buySell, orderType;
		Long time;
		Float amount;
		
		SimpleDateFormat d = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
		String date = new String();
		
		int i = 0;
		for (Order order : openOrders) {
			//Generate a date proper date
			time = order.getOpenTime();
			date = d.format(new Date(time));
			amount = order.getAmount();
			buySell = order.getBType();
			orderType = order.getOType();
			
			info[i][0] = (i+1)+"";
			info[i][1] = date;
			info[i][2] = order.getRatio();
			info[i][3] = order.getRate() + "";
			info[i][4] = amount.toString();
			
			//Buy/Sell
			switch(buySell){
				case 1:
					info[i][5] = "B";
					break;
				case 2:
					info[i][5] = "S";
					break;
			}
			
			//Order type
			switch(orderType){
				case 1:
					info[i][6] = "M";
					break;
				case 2:
					info[i][6] = "TS";
					break;
				case 3:
					info[i][6] = "L";
					break;
			}
			
			i++;	
		}
		return info;
	}
	
	/**
	 * Generate the components used to cancel orders
	 */
	public void createCloseOrders(){
		String [] rowNumbers = new String[table.getRowCount()];
		
    	for(int i = 0; i < rowNumbers.length; i++){
    		rowNumbers[i] = (i + 1) + "";
    	}
    	
    	//Create the components to cancel orders
    	closeOrder = new JButton("Cancel Order");
    	closeOrder.addActionListener(this);
    
    	//Set all the components' bounds
    	closeOrder.setBounds(290, 302, 120, 30);
	}
}
